package thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liweimin
 * @date 2021/5/8 14:27
 * @since
 */
public class Test05 {

    public static void main(String[] args) throws InterruptedException {
        Service service = new Service();

        new Thread(service::m).start();

        TimeUnit.MILLISECONDS.sleep(500);

        new Thread(service::m).start();
    }

    static class Service {
        private ReentrantLock lock = new ReentrantLock();

        public void m() {
            try {
                if (lock.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + "获得锁");
                    TimeUnit.SECONDS.sleep(3);
                } else {
                    System.out.println(Thread.currentThread().getName() + "未获得锁");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }
}
